package com.szholly.pro.watergas_server.ps.android.service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.szholly.pro.watergas_server.ps.android.bean.RuntimeDataBean;
import com.szholly.pro.watergas_server.ps.android.common.NumUtils;
import com.szholly.pro.watergas_server.ps.android.controller.SewageController;
import com.szholly.pro.watergas_server.ps.android.controller.SewageService;
import com.szholly.pro.watergas_server.ps.service.RemoteService;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.general.RowBase;

/**
 * 实时数据
 * 
 * 2017/6/12 <br/>
 *
 * @author Joey Huang QQ:273179370）
 */
@Service
public class MoveDataRuntimeService {
	public static final List<String> PARAMETER_LIST = Arrays.asList("101", "001", "ss", "do");


	// {"dateTime":"2017-04-14 16:07:33" ,"stationCode":"站点编号"
	// ,"valueList":[{"id":" ", "name":" ", "value":" ", "isAlarm":"0或1", }]}
	public List<Map<String, Object>> getHomeRuntimeDataList(List<RowBase> rows) throws Exception {
		List<Map<String, Object>> valueList = new ArrayList<>();
		for (RowBase rowBase : rows) {
			String deviceNum = rowBase.getSafeString("DEVICE_NUM");
			String stationCode = rowBase.getSafeString("site_id");
			SewageService manager = SewageController.getSewageManager();
			Map<String, Object> map = new HashMap<>();
			map.put("valueList", filterParameter(manager.getRuntimeDataList(deviceNum)));
			map.put("dateTime", manager.getRuntimeDataTime(deviceNum));
			map.put("stationCode", stationCode);
			valueList.add(map);
		}
		return valueList;
	}
	

	// 筛选出指定参数的数据
	public List<Map<String, String>> filterParameter(List<Map<String, String>> valueList) throws Exception {
		List<Map<String, String>> resultList = new ArrayList<>();
		if (!CollectionUtils.isEmpty(valueList)) {
			for (Map<String, String> bean : valueList) {
				String parameterCode = bean.get("id");
				if (PARAMETER_LIST.contains(parameterCode)) {
					resultList.add(bean);
				}
			}
		}
		return resultList;
	}

	/**
	 * 获取实时数据详情
	 * 
	 * 每个RowBase 包含以下信息
	 * 
	 * String leftLabel 左边的label
	 * 
	 * String rightLabel 右边的label
	 * 
	 * List<RuntimeDataBean> valueList 展示于界面上的数据
	 * 
	 * 包含两种数据(leftValue leftIsAlarm rightValue rightIsAlarm name)
	 */
	@SuppressWarnings("unchecked")
	public List<RowBase> getRuntimeDataDetail(List<RowBase> deviceList) throws Exception {
		// 返回的结果
		List<RowBase> resultList = new ArrayList<>();
		RowBase result = null;
		String leftDateTime = null;
		for (int i = 0; i < deviceList.size(); i++) {
			RowBase deviceRow = deviceList.get(i);
			String deviceNum = deviceRow.getSafeString("DEVICE_NUM");
			String stationName = deviceRow.getSafeString("STATION_NAME");

			String label = stationName;
			// if (isSurface) {
			// label = stationName;
			// } else {
			// int indexOf = stationName.indexOf("水口");
			// if (indexOf >= 1) {
			// label = stationName.substring(indexOf - 1, stationName.length());
			// }
			// }

			// 实时数据
			List<Map<String, String>> runtimeDataList = getRuntimeDataList(deviceNum);
			// 实时数据对应的时间
			String dataTime = getRuntimeDataTime(deviceNum);

			boolean nowLeft = i % 2 == 0;
			Map<String, RuntimeDataBean> runtimeDataMap;
			if (nowLeft) {
				result = new RowBase();
				runtimeDataMap = new HashMap<>();
				result.put("leftLabel", label);
				result.put("valueList", runtimeDataMap);
				leftDateTime = dataTime;
				resultList.add(result);			
				for (Map<String, String> value : runtimeDataList) {		
					String parameterCode = value.get("id");
					RuntimeDataBean valueBean = new RuntimeDataBean();
					valueBean.setLeftValue(value.get("value"));
					valueBean.setLeftIsAlarm(value.get("isAlarm"));
					valueBean.setRightValue("-");
					valueBean.setRightIsAlarm("0");
					valueBean.setName(value.get("name"));
					runtimeDataMap.put(parameterCode, valueBean);
				}
			} else {
				runtimeDataMap = (Map<String, RuntimeDataBean>) result.get("valueList");
				result.put("rightLabel", label);
				for (Map<String, String> value : runtimeDataList) {
					String parameterCode = value.get("id");
					RuntimeDataBean valueBean;
					if (!runtimeDataMap.containsKey(parameterCode)) {
						valueBean = new RuntimeDataBean();
						valueBean.setLeftValue("-");
						valueBean.setLeftIsAlarm("0");
						valueBean.setName(value.get("name"));
						runtimeDataMap.put(parameterCode, valueBean);
					} else {
						valueBean = runtimeDataMap.get(parameterCode);
					}
					valueBean.setRightIsAlarm(value.get("isAlarm"));
					valueBean.setRightValue(value.get("value"));
				}
			}

			// 将Map转换成List
			if (!nowLeft || i == deviceList.size() - 1) {// 如果是右边或者是最后一个
				RuntimeDataBean dateTimeBean = new RuntimeDataBean();
				dateTimeBean.setName("数据时间");
				dateTimeBean.setLeftValue(leftDateTime);
				dateTimeBean.setLeftIsAlarm("0");

				List<RuntimeDataBean> valueList = new ArrayList<>(runtimeDataMap.values());
				if (!nowLeft) {// 右边
					dateTimeBean.setRightValue(dataTime);
					dateTimeBean.setRightIsAlarm("0");
				} else {
					dateTimeBean.setRightValue("-");
					dateTimeBean.setRightIsAlarm("0");
				}
				valueList.add(0, dateTimeBean);
				result.put("valueList", valueList);
			}
		}
		return resultList;
	}

	// 获取实时数据{id,name,value,isAlarm}
	public List<Map<String, String>> getRuntimeDataList(String deviceNum) throws Exception {
		HashMap<String, RowBase> dataMap = RemoteService.getStationRealTimeData(deviceNum);
		List<Map<String, String>> valueList = new ArrayList<Map<String, String>>();
		if (!CollectionUtils.isEmpty(dataMap)) {
			Iterator<Entry<String, RowBase>> iterator = dataMap.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, RowBase> next = iterator.next();
				RowBase rowBase = next.getValue();
				Map<String, String> beanMap = createRuntimeDataMap(rowBase);
				valueList.add(beanMap);
			}
		}
		return valueList;
	}

	private Map<String, String> createRuntimeDataMap(RowBase rowBase) {
		Map<String, String> resultMap = new HashMap<String, String>();
		String unit = rowBase.getSafeString("UNIT");
		String valueStr = rowBase.getSafeString("MEAS_NORMAL");

		// 是否报警
		Double alarmUp = NumUtils.toDouble(rowBase.getSafeString("ALARMUP"), Double.MAX_VALUE);
		Double alarmDown = NumUtils.toDouble(rowBase.getSafeString("ALARMDOWN"), Double.MIN_VALUE);
		Double value = NumUtils.toDouble(valueStr, null);
		String isAlarm = "0";
		if (value != null && (value < alarmDown || value > alarmUp)) {
			isAlarm = "1";
		}
		resultMap.put("isAlarm", isAlarm);

		// 参数值(值+单位)并避免出现科学计数法
		String wholeValue = optWholeValue(valueStr);
		if (StringUtils.IsNullOrSpace(wholeValue)) {
			resultMap.put("value", "");
		} else if (StringUtils.IsNullOrSpace(unit)) {
			resultMap.put("value", wholeValue);
		} else {
			resultMap.put("value", wholeValue + unit);
		}
		// 参数名
		resultMap.put("name", rowBase.getSafeString("POLLNAME"));
		// 参数ID
		resultMap.put("id", (String) rowBase.get("POLL"));
		return resultMap;
	}

	// 返回完整的数值，防止出现科学计数法
	private String optWholeValue(String value) {
		if (value == null || !value.contains("E")) {
			return value;
		}
		Double optDouble = NumUtils.toDouble(value, null);
		if (optDouble == null) {
			return null;
		}
		DecimalFormat df = new DecimalFormat("########.00");
		return df.format(optDouble.doubleValue());
	}

	// 获取当前实时数据的时间
	public String getRuntimeDataTime(String deviceNum) throws Exception {
		List<RowBase> dateTimeList = RemoteService.getInstance().getStationHouseData(deviceNum);
		return dateTimeList.get(0).getSafeString("DATATIME");
	}

}
